<template>
  <div class="menu-manage">
    <el-card class="menu-card">
      <template #header>
        <div class="card-header">
          <span class="title">菜单管理</span>
        </div>
      </template>

      <div class="toolbar">
        <el-button 
          type="primary" 
          class="add-button" 
          @click="handleAdd"
        >
          新增
        </el-button>
      </div>

      <el-table
        :data="menuList"
        row-key="id"
        border
        :show-overflow-tooltip="true"
        :tree-props="{ 
          children: 'children', 
          indent: 16,
          hasChildren: (row: MenuItem) => Boolean(row.children?.length)
        }"
        :default-expand-all="false"
        class="menu-table"
      >
        <el-table-column prop="name" label="菜单名称" min-width="180" align="left">
          <template #default="{ row }">
            <div class="menu-name-cell">
              <span class="menu-name" :style="{ paddingLeft: row.level ? `${row.level * 16}px` : '0' }">
                {{ row.name }}
              </span>
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="path" label="路由路径" min-width="180">
          <template #default="{ row }">
            <div class="cell-wrapper">
              {{ row.path || '-' }}
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="component" label="组件路径" min-width="180">
          <template #default="{ row }">
            <div class="cell-wrapper">
              {{ row.component || '-' }}
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="perms" label="权限标识" min-width="180">
          <template #default="{ row }">
            <div class="cell-wrapper">
              {{ row.perms || '-' }}
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="type" label="类型" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="getMenuTypeTag(row.type)" :class="`menu-type-${row.type}`">
              {{ getMenuTypeLabel(row.type) }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="sort" label="排序" width="80" align="center" />

        <el-table-column prop="visible" label="显示状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="!row.hidden ? 'success' : 'info'">
              {{ !row.hidden ? '显示' : '隐藏' }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="180" align="center" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
            <el-button type="primary" link @click="handleAdd(row)">新增</el-button>
            <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-dialog 
      :title="dialogTitle" 
      v-model="dialogVisible"
      width="600px"
    >
      <el-form 
        ref="menuFormRef"
        :model="menuForm"
        :rules="menuRules"
        label-width="100px"
      >
        <el-form-item label="上级菜单">
          <el-tree-select
            v-model="menuForm.parentId"
            :data="menuList"
            :props="{
              value: 'id',
              label: 'name',
              children: 'children'
            }"
            placeholder="请选择上级菜单"
            check-strictly
            default-expand-all
            clearable
          />
        </el-form-item>

        <el-form-item label="菜单类型" prop="type">
          <el-radio-group v-model="menuForm.type">
            <el-radio :label="0">目录</el-radio>
            <el-radio :label="1">菜单</el-radio>
            <el-radio :label="2">按钮</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="菜单名称" prop="name">
          <el-input v-model="menuForm.name" placeholder="请输入菜单名称" />
        </el-form-item>

        <el-form-item label="路由路径" prop="path" v-if="menuForm.type !== 2">
          <el-input v-model="menuForm.path" placeholder="请输入路由路径" />
        </el-form-item>

        <el-form-item label="组件路径" prop="component" v-if="menuForm.type === 1">
          <el-input v-model="menuForm.component" placeholder="请输入组件路径" />
        </el-form-item>

        <el-form-item label="权限标识" prop="perms">
          <el-input v-model="menuForm.perms" placeholder="请输入权限标识" />
        </el-form-item>

        <el-form-item label="菜单图标" prop="icon" v-if="menuForm.type !== 2">
          <icon-select v-model="menuForm.icon" />
        </el-form-item>

        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="menuForm.sort" :min="0" :max="999" />
        </el-form-item>

        <el-form-item label="显示状态">
          <el-radio-group v-model="menuForm.hidden">
            <el-radio :label="false">显示</el-radio>
            <el-radio :label="true">隐藏</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getMenuTree, addMenu, updateMenu, deleteMenu } from '@/api/menu'
import IconSelect from '@/layout/components/IconSelect.vue'

// 定义菜单数据类型
interface MenuItem {
  id: number
  parentId: number
  name: string
  path: string
  component: string
  perms: string
  type: number
  sort: number
  visible: number
  children?: MenuItem[]
}

const menuList = ref<MenuItem[]>([])
const dialogVisible = ref(false)
const dialogTitle = ref('')
const menuFormRef = ref()

// 定义菜单表单接口
interface MenuForm {
  id?: number
  parentId: number
  name: string
  path: string
  component: string
  perms: string
  icon: string
  type: number
  sort: number
  visible: number
  status: number
  redirect: string
  title: string
  hidden: boolean
}


// 菜单表单引用
const menuForm = ref<MenuForm>({
  id: undefined,
  parentId: 0,
  name: '',
  path: '',
  component: '',
  perms: '',
  icon: '',
  type: 0,
  sort: 0,
  visible: 1,
  status: 1,
  redirect: '',
  title: '',
  hidden: false
})

const menuRules = {
  name: [{ required: true, message: '请输入菜单名称', trigger: 'blur' }],
  path: [{ required: true, message: '请输入路由路径', trigger: 'blur' }],
  type: [{ required: true, message: '请选择菜单类型', trigger: 'change' }]
}

const getMenuTypeTag = (type: number) => {
  const typeMap: Record<number, string> = {
    0: 'success',
    1: 'primary',
    2: 'warning'
  }
  return typeMap[type] || 'info'
}

const getMenuTypeLabel = (type: number) => {
  const typeMap: Record<number, string> = {
    0: '目录',
    1: '菜单',
    2: '按钮'
  }
  return typeMap[type] || '未知'
}

const getMenuData = async () => {
  try {
    const { data } = await getMenuTree()
    console.log('菜单数据:', data) // 调试用
    if (Array.isArray(data)) {
      menuList.value = data
    } else {
      console.error('菜单数据格式错误')
    }
  } catch (error) {
    console.error('获取菜单列表失败:', error)
  }
}

const handleAdd = (row?: any) => {
  dialogTitle.value = '添加菜单'
  menuForm.value = {
    id: undefined,
    parentId: row?.id || 0,
    name: '',
    path: '',
    component: '',
    perms: '',
    type: row ? 1 : 0,
    icon: '',
    sort: 0,
    visible: 1,
    status: 1,
    redirect: '',
    title: '',
    hidden: false
  }
  dialogVisible.value = true
}

const handleEdit = (row: any) => {
  dialogTitle.value = '编辑菜单'
  menuForm.value = { ...row }
  dialogVisible.value = true
}

const handleDelete = async (row: any) => {
  try {
    await ElMessageBox.confirm('确认要删除该菜单吗？', '提示', {
      type: 'warning'
    })
    await deleteMenu(row.id)
    ElMessage.success('删除成功')
    getMenuData()
  } catch (error) {
    console.error('删除失败:', error)
  }
}

const handleSubmit = async () => {
  if (!menuFormRef.value) return
  
  try {
    await menuFormRef.value.validate()
    if (menuForm.value.id) {
      await updateMenu(menuForm.value)
      ElMessage.success('更新成功')
    } else {
      await addMenu(menuForm.value)
      ElMessage.success('添加成功')
    }
    dialogVisible.value = false
    getMenuData()
  } catch (error) {
    console.error('提交失败:', error)
  }
}



onMounted(() => {
  getMenuData()
})
</script>

<style lang="scss" scoped>
.menu-manage {
  padding: 20px;
  background-color: #f5f7fa;

  .menu-card {
    .card-header {
      .title {
        font-size: 18px;
        font-weight: bold;
        color: #303133;
      }
    }

    .toolbar {
      margin-bottom: 20px;

      .add-button {
        padding: 8px 16px;
        font-size: 14px;
      }
    }

    .menu-table {
      :deep(.el-table) {
        &::before {
          display: none;
        }
        
        .el-table__header {
          th {
            background-color: #f5f7fa;
            color: #606266;
            font-weight: 500;
            height: 50px;
            padding: 0;
          }
        }
        
        .el-table__body {
          td {
            padding: 0;
          }
        }

        .cell-wrapper {
          height: 50px;
          display: flex;
          align-items: center;
          padding: 0 10px;
          color: #606266;
          font-size: 14px;
        }

        .el-table__expand-icon {
          width: 24px;
          height: 24px;
          display: flex;
          align-items: center;
          justify-content: center;
          
          .el-icon {
            font-size: 14px;
            transition: transform 0.2s;
            color: #909399;
          }
          
          &.el-table__expand-icon--expanded {
            .el-icon {
              transform: rotate(90deg);
            }
          }
        }

        // 菜单类型标签样式
        .menu-type-0 {
          --el-tag-bg-color: var(--el-color-success-light-9);
          --el-tag-border-color: var(--el-color-success-light-5);
          --el-tag-text-color: var(--el-color-success);
        }
        
        .menu-type-1 {
          --el-tag-bg-color: var(--el-color-primary-light-9);
          --el-tag-border-color: var(--el-color-primary-light-5);
          --el-tag-text-color: var(--el-color-primary);
        }
        
        .menu-type-2 {
          --el-tag-bg-color: var(--el-color-warning-light-9);
          --el-tag-border-color: var(--el-color-warning-light-5);
          --el-tag-text-color: var(--el-color-warning);
        }

        .menu-name-cell {
          height: 50px;
          display: flex;
          align-items: center;
          padding: 0 10px;

          .menu-name {
            flex: 1;
            color: #606266;
            font-size: 14px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
          }
        }
      }
    }
  }
}
</style> 